package com.nfit.rabbitmq.producer;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * ClassName:FanoutProducer
 * Package:com.nfit.rabbitmq.producer
 * Description
 *
 * @Author L
 * @Create 2024/11/22 8:54
 */
public class FanoutProducer {

    /**
     * Exchange名称
     */
    private final static String EXCHANGE_NAME = "test_queue";

    public static void main(String[] args) throws Exception {
        //初始化连接工厂，并指定rabbitmq的主机地址，默认端口为5672
        //初始化链接工厂并设置rabbitmq的主机地址
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672); //通信接口,1572是rabbitmq端口
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        //创建连接对象，并使用连接对象构建一个消息通信的通道
        try(Connection conn = factory.newConnection();
            Channel channel = conn.createChannel()) {
            //创建交换机，类型为fanout
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
            //定义一个info的message
            String infoMessage = "info message...A";
            //定义一个error的message
            String errorMessage = "error message...B";
            //将消息发送到交换机，路由key可任意设置，通常设置为""
            channel.basicPublish(EXCHANGE_NAME, "test_a.queue", null, infoMessage.getBytes());
            channel.basicPublish(EXCHANGE_NAME, "test_b.queue", null, errorMessage.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
